<template>
  <div class="chat-panel" :class="{ 'chat-panel-open': isOpen }">
    <div class="chat-header">
      <div class="chat-title">消息中心</div>
      <div class="chat-actions">
        <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-badge">
          <el-icon @click="markAllAsRead"><Bell /></el-icon>
        </el-badge>
        <el-icon @click="closeChat"><Close /></el-icon>
      </div>
    </div>
    
    <div class="chat-body" ref="chatBodyRef">
      <div v-if="messages.length === 0" class="empty-messages">
        <el-empty description="暂无消息" />
      </div>
      <template v-else>
        <div v-for="(message, index) in messages" :key="index" class="message-item" :class="[message.type]">
          <div class="message-header">
            <div class="avatar">
              <img :src="message.avatar || defaultAvatar" alt="头像">
            </div>
            <div class="sender-info">
              <div class="sender-name">{{ message.sender }}</div>
              <div class="message-time">{{ formatTime(message.time) }}</div>
            </div>
          </div>
          <div class="message-content" v-html="message.content"></div>
          <div class="message-status" v-if="message.type === 'sent'">
            <el-icon v-if="message.status === 'sent'"><Check /></el-icon>
            <el-icon v-else-if="message.status === 'delivered'"><CircleCheck /></el-icon>
            <el-icon v-else-if="message.status === 'read'"><CircleCheck style="color: #409EFF;" /></el-icon>
            <el-icon v-else-if="message.status === 'failed'" color="#F56C6C"><Warning /></el-icon>
          </div>
        </div>
      </template>
    </div>
    
    <div class="chat-footer">
      <div class="input-area">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="2"
          placeholder="请输入消息..."
          resize="none"
          @keyup.enter="sendMessage"
        />
      </div>
      <div class="action-buttons">
        <el-button type="primary" :disabled="!inputMessage.trim()" @click="sendMessage">发送</el-button>
        <el-dropdown trigger="click">
          <el-button plain>
            <el-icon><MoreFilled /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="clearMessages">清空聊天记录</el-dropdown-item>
              <el-dropdown-item @click="uploadFile">发送文件</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Check, CircleCheck, Warning, Bell, Close, MoreFilled } from '@element-plus/icons-vue';
import defaultAvatar from '@/assets/images/users.png';

// 属性定义
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  }
});

// 事件定义
const emit = defineEmits(['close', 'send-message']);

// 状态变量
const inputMessage = ref('');
const chatBodyRef = ref(null);
const unreadCount = ref(0);

// 示例消息数据
const messages = ref([
  // {
  //   id: 1,
  //   sender: '系统通知',
  //   content: '欢迎使用消息系统，有任何问题请随时联系我们。',
  //   time: new Date(Date.now() - 3600000 * 24),
  //   type: 'received',
  //   avatar: null,
  //   read: true
  // },
  // {
  //   id: 2,
  //   sender: '作业调度',
  //   content: '今日有新的作业任务已分配，请查看详情。',
  //   time: new Date(Date.now() - 3600000 * 2),
  //   type: 'received',
  //   avatar: null,
  //   read: false
  // }
]);

// 计算未读消息数量
watch(() => props.isOpen, (newVal) => {
  if (newVal) {
    calculateUnreadCount();
    scrollToBottom();
  }
});

// 格式化时间显示
const formatTime = (time) => {
  const date = new Date(time);
  const now = new Date();
  const diff = now - date;
  
  // 今天内的消息显示时间
  if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 一周内的消息显示星期几
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = ['日', '一', '二', '三', '四', '五', '六'];
    return `星期${days[date.getDay()]} ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`;
  }
  
  // 更早的消息显示完整日期
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
};

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return;
  
  const newMessage = {
    id: Date.now(),
    sender: '我',
    content: inputMessage.value,
    time: new Date(),
    type: 'sent',
    status: 'sent',
    read: true
  };
  
  messages.value.push(newMessage);
  emit('send-message', newMessage);
  inputMessage.value = '';
  
  nextTick(() => {
    scrollToBottom();
  });
  
  // 模拟自动回复
  setTimeout(() => {
    const autoReply = {
      id: Date.now() + 1,
      sender: '系统',
      content: '您的消息已收到，我们将尽快处理。',
      time: new Date(),
      type: 'received',
      avatar: null,
      read: props.isOpen
    };
    
    messages.value.push(autoReply);
    if (!props.isOpen) {
      unreadCount.value++;
    }
    
    nextTick(() => {
      if (props.isOpen) {
        scrollToBottom();
      }
    });
  }, 1000);
};

// 滚动到底部
const scrollToBottom = () => {
  if (chatBodyRef.value) {
    chatBodyRef.value.scrollTop = chatBodyRef.value.scrollHeight;
  }
};

const calculateUnreadCount = () => {
  if (props.isOpen) {
    messages.value.forEach(msg => {
      if (msg.type === 'received') {
        msg.read = true;
      }
    });
    unreadCount.value = 0;
  } else {
    unreadCount.value = messages.value.filter(msg => msg.type === 'received' && !msg.read).length;
  }
};

// 标记所有消息为已读
const markAllAsRead = () => {
  messages.value.forEach(msg => {
    if (msg.type === 'received') {
      msg.read = true;
    }
  });
  unreadCount.value = 0;
  ElMessage.success('已将所有消息标记为已读');
};

// 关闭聊天框
const closeChat = () => {
  emit('close');
};

// 清空聊天记录
const clearMessages = () => {
  ElMessageBox.confirm('确定要清空所有聊天记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    messages.value = [];
    ElMessage.success('聊天记录已清空');
  }).catch(() => {});
};

// 上传文件
const uploadFile = () => {
  ElMessage.info('文件上传功能开发中...');
};

// 组件挂载后
onMounted(() => {
  // calculateUnreadCount();
  // if (props.isOpen) {
  //   scrollToBottom();
  // }
});
</script>

<style lang="scss" scoped>
.chat-panel {
  position: fixed;
  bottom: 50px;
  left: 65px;
  width: 360px;
  height: 480px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 -2px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  transform: translateY(calc(100% + 60px));
  transition: transform 0.3s ease;
  
  &.chat-panel-open {
    transform: translateY(0);
  }
  
  .chat-header {
    height: 50px;
    background: linear-gradient(90deg, #409EFF, #53a8ff);
    color: white;
    border-radius: 12px 12px 0 0;
    padding: 0 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    
    .chat-title {
      font-weight: bold;
      font-size: 16px;
    }
    
    .chat-actions {
      display: flex;
      align-items: center;
      gap: 15px;
      
      .el-icon {
        cursor: pointer;
        font-size: 18px;
        
        &:hover {
          opacity: 0.8;
        }
      }
    }
  }
  
  .chat-body {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
    background-color: #f5f7fa;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0.2);
      border-radius: 3px;
    }
    
    .empty-messages {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .message-item {
      margin-bottom: 15px;
      max-width: 80%;
      
      &.received {
        align-self: flex-start;
        margin-right: auto;
        
        .message-content {
          background-color: white;
          border-radius: 0 12px 12px 12px;
          color: #333;
        }
      }
      
      &.sent {
        align-self: flex-end;
        margin-left: auto;
        
        .message-header {
          flex-direction: row-reverse;
          
          .sender-info {
            text-align: right;
          }
        }
        
        .message-content {
          background-color: #ecf5ff;
          border-radius: 12px 0 12px 12px;
          color: #333;
        }
      }
      
      .message-header {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        
        .avatar {
          width: 30px;
          height: 30px;
          border-radius: 50%;
          overflow: hidden;
          margin: 0 8px;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        
        .sender-info {
          .sender-name {
            font-size: 13px;
            font-weight: 500;
          }
          
          .message-time {
            font-size: 11px;
            color: #909399;
          }
        }
      }
      
      .message-content {
        padding: 10px 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        word-break: break-word;
        line-height: 1.5;
      }
      
      .message-status {
        font-size: 12px;
        text-align: right;
        margin-top: 2px;
        color: #909399;
      }
    }
  }
  
  .chat-footer {
    padding: 10px;
    border-top: 1px solid #ebeef5;
    background-color: white;
    
    .input-area {
      margin-bottom: 8px;
      
      .el-textarea__inner {
        resize: none;
        border-radius: 20px;
        padding: 8px 15px;
        
        &:focus {
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }
    }
    
    .action-buttons {
      display: flex;
      justify-content: space-between;
      
      .el-button {
        border-radius: 20px;
      }
    }
  }
}

// 动画效果
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.notification-badge :deep(.el-badge__content) {
  animation: pulse 1s infinite;
}
</style> 